package com.homedo.async.mysql.support.convertor.forfieldval;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Date;

/**
 * @author jgshun
 * @date 2020/1/20 11:51 AM
 */
public class DateResultFieldValConvertor implements ResultFieldValConvertorI {
    private static final DateResultFieldValConvertor INSTANCE = new DateResultFieldValConvertor();

    public static DateResultFieldValConvertor getInstance() {
        return INSTANCE;
    }

    @Override
    public Date convertor(Object columnVal) {
        if (columnVal instanceof LocalDateTime) {
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime timeZdt = ((LocalDateTime) columnVal).atZone(zoneId);
            return Date.from(timeZdt.toInstant());
        } else if (columnVal instanceof LocalDate) {
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime timeZdt = ((LocalDate) columnVal).atStartOfDay(zoneId);
            return Date.from(timeZdt.toInstant());
        } else if (columnVal instanceof LocalTime) {
            LocalTime localTime = (LocalTime) columnVal;
            LocalDate localDate = LocalDate.of(0, 0, 0);
            LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
            ZoneId zone = ZoneId.systemDefault();
            Instant instant = localDateTime.atZone(zone).toInstant();
            return Date.from(instant);
        } else if (columnVal instanceof Duration) {
            Duration duration = (Duration) columnVal;
            LocalTime localTime = LocalTime.ofNanoOfDay(duration.toNanos());
            LocalDate localDate = LocalDate.of(0, 0, 0);
            LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
            ZoneId zone = ZoneId.systemDefault();
            Instant instant = localDateTime.atZone(zone).toInstant();
            return Date.from(instant);
        } else if (columnVal instanceof String) {
            try {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(columnVal.toString());
            } catch (ParseException e) {
                throw new RuntimeException("[解析日期格式有误:预期格式(yyyy-MM-dd HH:mm:ss), 实际值" + columnVal.toString() + "]");
            }
        }

        throw new RuntimeException("[未知类型" + columnVal.getClass() + ", " + columnVal + "]");
    }

}
